package org.sample.springboot.validator;

import java.util.Set;

import javax.validation.ConstraintValidatorContext;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

import org.springframework.util.CollectionUtils;

public abstract class OptionalValidator {
	
	private Validator validator;
	
	public OptionalValidator() {
		ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
		validator = factory.getValidator();
	}

	public boolean isValid(boolean isEnabled, Object optionalFieldValue,
			String optionalFieldName, ConstraintValidatorContext context) {
		
		if (!isEnabled) {
			return true;
		}
		
		if (optionalFieldValue == null) {
			context.disableDefaultConstraintViolation();
			context.buildConstraintViolationWithTemplate(
					ValidatorConstants.EMPTY_ERROR_PREFIX + optionalFieldName.toUpperCase())
					.addPropertyNode(optionalFieldName)
					.addConstraintViolation();
			return false;
		}

		Set<ConstraintViolation<Object>> constraintViolations = validator.validate(optionalFieldValue);
		if (!CollectionUtils.isEmpty(constraintViolations)) {
			for (ConstraintViolation<Object> constraintViolation : constraintViolations) {
				context.disableDefaultConstraintViolation();
				context.buildConstraintViolationWithTemplate(constraintViolation.getMessageTemplate())
						.addPropertyNode(optionalFieldName)
						.addPropertyNode(constraintViolation.getPropertyPath().toString())
						.addConstraintViolation();
			}
			return false;
		}

		return true;
	}
	
}
